import React, { memo, useEffect } from 'react';
import { Row, Col, Form, Input } from 'antd';
import classnames from 'classnames';
import moment from 'moment';
import formItemType from './filter.js';

import styles from './index.less';

const FormItem = ({ item, isNeedLable, form, rest }) => {
  let { labelCol = 8, wrapperCol } = item;
  //默认宽度
  let formItemLayout = isNeedLable
    ? {
        labelCol: { span: labelCol },
        wrapperCol: { span: wrapperCol ? wrapperCol : 24 - labelCol },
      }
    : {};

  let selfProps = { ...formItemLayout };
  isNeedLable && (selfProps['label'] = item.name || '');

  if (form && item.type !== 'button' && item.id) {
    selfProps['name'] = item.id;
    item.options && (selfProps['rules'] = { ...item.options });
    const { getFieldDecorator } = form;
    return (
      <Form.Item
        {...selfProps}
        style={item.style}
        className={classnames(styles['form-item-wrap'], item.className)}
      >
        {formItemType({ ...rest, form: form })}
      </Form.Item>
    );
  }

  return (
    <Form.Item
      {...selfProps}
      style={item.style}
      className={classnames(styles['form-item-wrap'], item.className)}
    >
      {formItemType({ ...rest, form: form })}
    </Form.Item>
  );
};
//过滤是不是Item,还是单个组件
//过滤是不是需要权限
const FilterLayer = ({ item, form, index }) => {
  const type = item.type;
  const isNeedLable = item.type.toLowerCase().indexOf('item') !== -1;

  const { style, pos, labelCol = 6, wrapperCol = 18, ...rest } = item;

  //单表单
  return <FormItem item={item} isNeedLable={isNeedLable} rest={rest} form={form} />;
};
const Toolbar = props => {
  const [form] = Form.useForm();
  const { modules = [], fields, className, leftSpan, rightSpan } = props;
  let leftModule = modules.filter(item => {
    return item.pos === 'left' || !item.pos;
  });

  let rightModule = modules.filter(item => {
    return item.pos === 'right';
  });
  useEffect(() => {
    form.setFieldsValue({
      ...fields,
    });
  }, [fields]);

  return (
    <Row className={classnames(styles['tool-wrap'], className)}>
      <Form form={form} layout={'inline'} className={styles['form-wrap']}>
        <Col span={leftSpan || 24} key={'left'} className={styles['left']}>
          {leftModule.map((item, index) => {
            return (
              <FilterLayer key={index.toString(36) + index} item={item} index={index} form={form} />
            );
          })}
        </Col>
        <Col
          className={styles['right']}
          key={'right'}
          span={leftSpan && rightSpan ? rightSpan : 24 - (leftSpan || 0)}
        >
          {rightModule.map((item, index) => {
            return (
              <FilterLayer key={index.toString(36) + index} form={form} item={item} index={index} />
            );
          })}
        </Col>
      </Form>
    </Row>
  );
};

export default memo(Toolbar);
